/*!
 * \file te_core.h
 *
 * \brief TongEASY模块主文件
 *
 * All Rights Reserved Copyright (C) 2014 broada,Co.,Ltd.
 *
 * \version 1.0
 * \author songbb
 * \date 2016/09/24
 *
 */

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <arpa/inet.h>
#include <frct_detect_hash.h>

#include "frlog.h"
#include "frreport_comm.h"

#include "frct_comm.h"

#include "te_comm.h"
#include "te_header.h"
#include "te_packet.h"
#include "te_trans.h"
#include "config.h"

extern void *g_p_apm_context;

/*******************************************************************************
*  FUNC     :  te Session初始化
*  ARGS     :  *p_st_session                            (L7层session信息)
*  RTN      :  0                                        (FR_SUCC)
*              1                                        (FR_FAIL)
*  NOTE     :
*******************************************************************************/
FR_STATIC int __te_private_session_init(L7_session *p_st_session)
{
    TE_PRINT_INFO("session init\n");
    L7session_te_private *p_st_te_private = NULL;      // TE的私有信息
    L7_te_packet *p_st_te_packet = NULL;               // TE格式的packet包
    Frhash_header *p_hash_stmt = NULL;                 // TE的statement信息结构

    // 1. 初始化te格式的packet包
    if ((p_st_te_packet = (L7_te_packet *) frmalloc(sizeof(L7_te_packet))) == NULL)
    {
        TE_MALLOCK_ERR;
        goto error;
    }
    memset(p_st_te_packet, 0x00, sizeof(L7_te_packet));
    if (te_init_packet(p_st_te_packet) != FR_SUCC)
        goto error;

    // 2. 初始化statement hash
    if ((p_hash_stmt = (Frhash_header *) frmalloc(sizeof(Frhash_header))) == NULL)
    {
        TE_MALLOCK_ERR;
        goto error;
    }
    memset(p_hash_stmt, 0x00, sizeof(Frhash_header));
    if (frhash2_create(p_hash_stmt, APM_TE_HASH_SIZE) != FR_SUCC)
    {
        TE_FRLOG_ERROR("frhash2_create fail");
        goto error;
    }

    // 3. 创建和初始化te的私有信息
    if ((p_st_te_private = (L7session_te_private *) frmalloc(sizeof(L7session_te_private))) == NULL)
    {
        TE_MALLOCK_ERR;
        goto error;
    }
    memset(p_st_te_private, 0x00, sizeof(L7session_te_private));
    p_st_te_private->p_st_te_packet = p_st_te_packet;
    p_st_te_private->p_st_session = p_st_session;
    p_st_te_private->p_hash_stmt = p_hash_stmt;

    // 4. 设置L7_session的p_session_private信息
    frct_set_session_private(p_st_session, (void *)p_st_te_private);

    return FR_SUCC;
error:
    if (p_st_te_packet != NULL)
    {
        bytebuff_free(&(p_st_te_packet->p_st_packet));
        te_free((void **) &p_st_te_packet);
    }
    frhash2_free2(p_hash_stmt, te_stmt_node_free);
    te_free((void **) &p_st_te_private);
    return FR_FAIL;
}

int te_detect(Conntrack *p_st_conn
            , Apm_packet *p_analyze_in)
{
    TE_PRINT_INFO("te_detect...\n");

#if APM_TE_DBG
    char arr_ip_src[56], arr_ip_dst[56];
    snprintf(arr_ip_src, sizeof(arr_ip_src), "%s", int_ntoa(p_analyze_in->src_ip));
    snprintf(arr_ip_dst, sizeof(arr_ip_src), "%s", int_ntoa(p_analyze_in->dst_ip));
    TE_PRINT_TIMEVAL("PacketIn", p_analyze_in->st_timestamp);
    TE_PRINT_DBG("Src:[%s:%d] Dest:[%s:%d] Length:[%u]\n", arr_ip_src, p_analyze_in->src_port, arr_ip_dst, p_analyze_in->dst_port, p_analyze_in->ui_payload_len);
#endif

    if (te_header_detect(p_st_conn, p_analyze_in->p_payload, p_analyze_in->ui_payload_len) != APM_L7_IS_YES)
        goto unknown;

    TE_PRINT_INFO("te_detect success\n\n");
    return APM_L7_IS_YES;
unknown:
    TE_PRINT_INFO("te_detect failed\n\n");
    return APM_L7_IS_UNKNOWN;
}

int te_analyze(Conntrack *p_st_conn
                , Apm_packet *p_analyze_in
                , Frhash_header *p_st_hash_report)
{
    TE_PRINT_INFO("te_analyze\n");
    L7_session *p_st_session = NULL;
    L7session_te_private *p_st_session_private = NULL;
    L7_te_packet *p_st_te_packet = NULL;
    int i_unfragmented_ret = 0;
    int i_analyze_ret = APM_L7_ANALYZE_FAIL;                  // 本函数的返回值
    char arr_ip_src[56], arr_ip_dst[56];
    int i_payload_offset = 0;
    TE_detect_session *p_st_detect_sess = NULL;

    if(p_st_conn == NULL || p_analyze_in == NULL
      || p_st_hash_report == NULL)
        return APM_L7_ANALYZE_FAIL;

    p_st_session = frct_get_session(p_st_conn);
    snprintf(arr_ip_src, sizeof(arr_ip_src), "%s", int_ntoa(p_analyze_in->src_ip));
    snprintf(arr_ip_dst, sizeof(arr_ip_src), "%s", int_ntoa(p_analyze_in->dst_ip));

    TE_PRINT_TIMEVAL("PacketIn", p_analyze_in->st_timestamp);
    TE_PRINT_DBG("Src:[%s:%d] Dest:[%s:%d] SessionID:[%s]\n", arr_ip_src, p_analyze_in->src_port, arr_ip_dst, p_analyze_in->dst_port, p_st_session->arr_session_id);

    /*
    * 如果入力p_st_packet是FIN包, 说明本次connection结束,
    * 释放本次session信息. 如果入力p_st_packet是SYN包,说明新的
    * connection开始了, 释放上次可能残留的session信息
    */
    if (p_analyze_in->em_analyz_cmd == FRANALYZ_CMD_FIN || p_analyze_in->em_analyz_cmd == FRANALYZ_CMD_SYN)
    {
        i_analyze_ret = APM_L7_ANALYZE_SUCC;
        if (p_analyze_in->em_analyz_cmd == FRANALYZ_CMD_SYN)
            TE_PRINT_INFO("SYN PACKET\n");
        else if (p_analyze_in->em_analyz_cmd == FRANALYZ_CMD_FIN)
            TE_PRINT_INFO("FIN PACKET\n");

        if ((p_st_session_private = (L7session_te_private *) frct_get_session_private(p_st_session)) != NULL)
        {
            te_session_destory(p_st_session->p_session_private);
            p_st_session->p_session_private = NULL;
        }
        TE_PRINT("### i_analyze_ret:[%d]\n\n", i_analyze_ret);
        return i_analyze_ret;
    }

    // 本次链路的第一个有效packet包,创建链路
    if (p_st_session->p_session_private == NULL)
    {
        // 初始化te的session数据
        if (__te_private_session_init(p_st_session) != FR_SUCC)
            goto te_analyze_fail;

        // 设置session uuid
        fruuid(p_st_session->arr_session_id);
    }

    // 打印方向
    switch (p_analyze_in->i_direction)
    {
        case FR_DIRECT_CLIENT2SRV:
            TE_PRINT("client["KLIMEGREEN"%s:%d"RESET"] to server["KLIMEGREEN"%s:%d"RESET"] ["KYELLOW"%d"RESET"] ->>>>>>>>>>>>>>>>>>>>>>>\n",
                      arr_ip_src,
                      p_analyze_in->src_port,
                      arr_ip_dst,
                      p_analyze_in->dst_port,
                      p_analyze_in->ui_payload_len);
            break;
        case FR_DIRECT_SRV2CLIENT:
            TE_PRINT("server["KLIMEGREEN"%s:%d"RESET"] to client["KLIMEGREEN"%s:%d"RESET"] ["KYELLOW"%d"RESET"] <<<<<<<<<<<<<<<<<<<<<<<-\n",
                      arr_ip_src,
                      p_analyze_in->src_port,
                      arr_ip_dst,
                      p_analyze_in->dst_port,
                      p_analyze_in->ui_payload_len);
            break;
        default:
            TE_PRINT("unknown direction, src["KLIMEGREEN"%s:%d"RESET"], dest["KLIMEGREEN"%s:%d"RESET"]\n",
                      arr_ip_src,
                      p_analyze_in->src_port,
                      arr_ip_dst,
                      p_analyze_in->dst_port);
            goto te_analyze_fail;
    }

    p_st_session_private = (L7session_te_private *) frct_get_session_private(p_st_session);
    p_st_te_packet = p_st_session_private->p_st_te_packet;

    if ((p_st_detect_sess = (TE_detect_session *) frct_detect_data_get(p_st_conn, MODULE_L7PROTO)) != NULL)
        frct_detect_hash_del(p_st_conn, MODULE_L7PROTO);

    while (i_payload_offset < (int) p_analyze_in->ui_payload_len)
    {
        i_unfragmented_ret = te_packet_unfragment(p_analyze_in, p_st_te_packet, i_payload_offset);
        if (i_unfragmented_ret == APM_TE_CHECK_FRAGMENT_NEED_NEXT_PACKET)
            goto te_analyze_todo;
        else if (i_unfragmented_ret == APM_TE_CHECK_FRAGMENT_ERROR)
            goto te_analyze_fail;
        else if (i_unfragmented_ret == APM_TE_CHECK_FRAGMENT_SKIP)
            goto te_analyze_success;

        switch (p_st_te_packet->st_te_header.pkt_type)
        {
            case TE_PKT_TYPE_SYNC_ASYNC_REQ:
            case TE_PKT_TYPE_CVS_REQ:
                if (frcap_set_cs_srv(p_st_conn, p_analyze_in->dst_ip, p_analyze_in->dst_port) != FR_SUCC)
                    goto te_analyze_fail;
                if (te_sync_async_req(p_st_conn, p_st_te_packet, p_st_hash_report) == FR_SUCC)
                    i_analyze_ret = APM_L7_ANALYZE_SET_REQ(APM_L7_ANALYZE_SUCC);
                break;
            case TE_PKT_TYPE_SYNC_ASYNC_RESP:
            case TE_PKT_TYPE_CVS_RESP:
                if (te_sync_async_resp(p_st_conn, p_st_te_packet, p_st_hash_report) == FR_SUCC)
                    i_analyze_ret = APM_L7_ANALYZE_SET_RESP(APM_L7_ANALYZE_SUCC);
                break;
            case TE_PKT_TYPE_SYNC_ASYNC_COMMIT_REQ:
            case TE_PKT_TYPE_SYNC_ASYNC_COMMIT_RESP:
            case TE_PKT_TYPE_SYNC_ASYNC_ABORT_REQ:
            case TE_PKT_TYPE_SYNC_ASYNC_ABORT_RESP:
            case TE_PKT_TYPE_CVS_CONN_REQ:
            case TE_PKT_TYPE_CVS_CONN_RESP:
            case TE_PKT_TYPE_CVS_DISCONN:
                goto te_analyze_todo;
            default:
                TE_PRINT_EMERG("invalid hdr type\n");
                goto te_analyze_fail;
        }

        i_payload_offset += bytebuff_length(p_st_te_packet->p_st_packet);
    }

    if (APM_L7_ANALYZE_IS_REQ(i_analyze_ret) || APM_L7_ANALYZE_IS_RESP(i_analyze_ret))
        goto te_analyze_success;

te_analyze_todo:
    TE_PRINT("### i_analyze_ret todo:[%d]\n\n", APM_L7_ANALYZE_TODO);
    return APM_L7_ANALYZE_TODO;

te_analyze_success:
    TE_PRINT("### i_analyze_ret success:[%d]\n\n", i_analyze_ret);
    return i_analyze_ret;

te_analyze_fail:
    if (te_packet_is_in_fragment(p_st_te_packet))
    {
        if (bytebuff_setPosition(p_st_te_packet->p_st_packet, 0) != FR_SUCC)
        {
            p_st_te_packet->fragment_state = APM_TE_FRAGMENT_INIT;
            return APM_L7_ANALYZE_FAIL;
        }
        goto te_analyze_todo;
    }
    else
    {
        TE_PRINT_PACKET("error packet", p_st_te_packet);
        te_init_packet(p_st_te_packet);
    }

    TE_PRINT_EMERG("### i_analyze_ret fail:[%d]\n\n", APM_L7_ANALYZE_FAIL);
    return APM_L7_ANALYZE_FAIL;
}

/*******************************************************************************
*  FUNC     :  释放 L7_te_packet
*  ARGS     :  **pp_st_te_packet              (L7_te_packet)
*  RTN      :  void
*  NOTE     :
*******************************************************************************/
FR_STATIC void __te_destroy_packet(L7_te_packet **pp_st_te_packet)
{
    if (pp_st_te_packet == NULL || *pp_st_te_packet == NULL)
        return;

    L7_te_packet *p_st_te_packet = *pp_st_te_packet;
    bytebuff_free(&(p_st_te_packet->p_st_packet));
    te_free((void **) pp_st_te_packet);
    return;
}

/*******************************************************************************
*  FUNC     :  释放 L7_te_stmt
*  ARGS     :  *p_hash_stmt              (L7_te_stmt)
*  RTN      :  void
*  NOTE     :
*******************************************************************************/
FR_STATIC void __te_destroy_stmt(Frhash_header *p_hash_stmt)
{
    frhash2_free2(p_hash_stmt, te_stmt_node_free);
}

int te_session_destory(void *p_st_session_private_in)
{
    TE_PRINT(KBLUE "\nte_session_destory run\n" RESET);
    if (p_st_session_private_in == NULL)
        return FR_SUCC;

    L7session_te_private *p_st_private = (L7session_te_private *) p_st_session_private_in;

    __te_destroy_packet(&(p_st_private->p_st_te_packet));

    __te_destroy_stmt(p_st_private->p_hash_stmt);

    te_free((void **) &p_st_private);

    TE_PRINT_INFO("leave te_session_destory\n");
    return FR_SUCC;
}
